<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use Jrk\Email;
use Jrk\Times;
use library\File;
use think\facade\Cache;
use think\facade\Env;
use library\service\SystemService;
use library\service\AdminService;
use think\Db;

const ERRNO_MAP = [
    'OK' => '成功',
    'DBERR' => '数据库查询错误',
    'NODATA' => '无数据',
    'DATAEXIST' => '数据已存在',
    'DATAERR' => '数据错误',
    'SESSIONERR' => '用户未登录',
    'LOGINERR' => '用户登录失败',
    'PARAMERR' => '参数错误',
    'USERERR' => '用户不存在或未激活',
    'ROLEERR' => '用户身份错误',
    'PWDERR' => '密码错误',
    'REQERR' => '非法请求或请求次数受限',
    'IPERR' => 'IP受限',
    'THIRDERR' => '第三方系统错误',
    'IOERR' => '文件读写错误',
    'SERVERERR' => '内部错误',
    'UNKOWNERR' => '未知错误',
];

const ERRNO = [
    'OK' => '0',
    'DBERR' => '4001',
    'NODATA' => '4002',
    'DATAEXIST' => '4003',
    'DATAERR' => '4004',
    'SESSIONERR' => '4101',
    'LOGINERR' => '4102',
    'PARAMERR' => '4103',
    'USERERR' => '4104',
    'ROLEERR' => '4105',
    'PWDERR' => '4106',
    'REQERR' => '4201',
    'IPERR' => '4202',
    'THIRDERR' => '4301',
    'IOERR' => '4302',
    'SERVERERR' => '4500',
    'UNKOWNERR' => '4501',
];

//加载额外的
if (is_file(Env::get('app_path') . 'function.php')) {
    include_once Env::get('app_path') . 'function.php';
}

// 应用公共文件

if (!function_exists('rm_empty_dir')) {
    /**
     * @param $path
     * @return bool
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/9
     * @name: rm_empty_dir
     * @describe:删除所有空目录
     */
    function rm_empty_dir($path)
    {
        if (!(is_dir($path) && ($handle = opendir($path)) !== false)) {
            return false;
        }
        while (($file = readdir($handle)) !== false) {
            if (!($file != '.' && $file != '..')) {
                continue;
            }
            $curfile = $path . DS_PROS . $file;// 当前目录
            if (!is_dir($curfile)) {
                continue;
            }
            rm_empty_dir($curfile);
            if (count(scandir($curfile)) == 2) {
                rmdir($curfile);
            }
        }
        closedir($handle);
    }
}


if (!function_exists('hook')) {
    /**
     * @param $behavior
     * @param $params
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/9
     * @name: hook
     * @describe:钩子行为
     */
    function hook($behavior, $params)
    {
        think\facade\Hook::exec($behavior, $params);
    }
}


if (!function_exists('sendMaile')) {
    /**
     * @param $subject
     * @param $body
     * @param $to
     * @param null $attachment
     * @return array
     * @throws \PHPMailer\PHPMailer\Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/14 0014
     * @name: sendMaile
     * @describe:邮件发送
     */
    function sendMaile($subject,$body,$to,&$attachment=null)
    {
        $maile = Email::instance();
        $maile->subject($subject);
        $maile->body($body);
        $maile->to($to);

        if (isset($attachment) && !empty($attachment)) {
            if (is_array($attachment)) {
                foreach ($attachment as $v) {
                    $maile->attachment($v);
                }
            } else {
                $maile->attachment($attachment);
            }
        }
        $result = $maile->send();
        if ($result) {
           $arr= ['code'=>1,'msg'=>'发送成功'];
        } else {
            $arr= ['code'=>0,'msg'=>$maile->getError()];
        }
        return  $arr;
    }
}


if (!function_exists("formBytes")) {
    /**
     * @param $size
     * @param string $delimiter
     * @return string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/9
     * @name: format_bytes
     * @describe:格式化数据
     */
    function formBytes($size, $delimiter = '')
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
        for ($i = 0; $size >= 1024 && $i < 5; $i++) {
            $size /= 1024;
        }

        return round($size, 2) . $delimiter . $units[$i];
    }
}

if (!function_exists("FriendTime")) {
    /**
     * @param $time
     * @return false|string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/28
     * @name: FriendTime
     * @describe:时间友好
     */
    function FriendTime($time)
    {
        return Times::friendlyDate($time);
    }
}

if (!function_exists("clearCache")) {

    /**
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/1/14
     * @name: clearCache
     * @describe:清除缓存
     */
    function clearCache()
    {
        Cache::clear();
    }
}


if (!function_exists('local_image')) {
    /**
     * @param $url
     * @param bool $force
     * @param int $expire
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/6
     * @name: local_image
     * @describe:下载远程文件到本地
     */
    function localImage($url, $force = false, $expire = 0)
    {
        $result = File::down($url, $force, $expire);
        if (isset($result['url'])) {
            return $result['url'];
        } else {
            return $url;
        }
    }
}


if (!function_exists('sysQueue')) {
    /**
     * @param $title
     * @param $loade
     * @param int $later
     * @param array $data
     * @param int $double
     * @return bool
     * @throws \think\Exception
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/6
     * @name: sysQueue
     * @describe:创建异步处理任务
     */
    function sysQueue($title, $loade, $later = 0, $data = [], $double = 1)
    {
        $map = [['title', 'eq', $title], ['status', 'in', [1, 2]]];
        if (empty($double) && db('SystemQueue')->where($map)->count() > 0) {
            throw new \think\Exception('该任务已经创建，请耐心等待处理完成！');
        }
        $result = db('SystemQueue')->insert([
            'title' => $title, 'preload' => $loade,
            'data' => json_encode($data, JSON_UNESCAPED_UNICODE),
            'time' => $later > 0 ? time() + $later : time(),
            'double' => intval($double), 'create_at' => date('Y-m-d H:i:s'),
        ]);
        return $result !== false;
    }
}


if (!function_exists('base64_image')) {
    /**
     * @param $content
     * @param string $dirname
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/6
     * @name: base64_image
     * @describe:base64 图片上传接口
     */
    function base64_image($content, $dirname = 'base64/')
    {
        try {
            if (preg_match('|^data:image/(.*?);base64,|i', $content)) {
                list($ext, $base) = explode('|||', preg_replace('|^data:image/(.*?);base64,|i', '$1|||', $content));
                $info = File::save($dirname . md5($base) . '.' . (empty($ext) ? 'tmp' : $ext), base64_decode($base));
                return $info['url'];
            } else {
                return $content;
            }
        } catch (\Exception $e) {
            return $content;
        }
    }
}


if (!function_exists('sysData')) {
    /**
     * @param $name
     * @param null $value
     * @return bool|mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12
     * @name: sysData
     * @describe:JSON 数据读取与存储
     */
    function sysData($name, $value = null)
    {
        if (is_null($value)) {
            return SystemService::instance()->getData($name);
        } else {
            return SystemService::instance()->setData($name, $value);
        }
    }
}


if (!function_exists('auth')) {
    /**
     * @param $node
     * @return bool
     * @throws ReflectionException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12
     * @name: auth
     * @describe:节点访问权限检查
     */
    function auth($node)
    {
        return AdminService::instance()->check($node);
    }
}


if (!function_exists('Logs')) {
    /**
     * @param $content
     * @param string $dir
     * @param string $file
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12 0012
     * @name: Logs
     * @describe:记录日志文件
     */
    function Logs($content, $dir = 'jrk', $file = '')
    {
        if (empty($file)) {
            $file = date("Y_m_d", time());
        }
        $file_path = ROOT_PATH . 'Logs/' . $dir;
        if (!is_dir($file_path)) {
            mkdir($file_path, 0777, true);
        }
        @file_put_contents(
            $file_path . '/' . $file . '.log',
            date('Y-m-d H:i:s', time()) . ' ' . var_export($content, true) . "\r\n",
            FILE_APPEND
        );
    }
}


if (!function_exists('addLog')) {

    /**
     * @param string $title
     * @param string $content
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/12 0012
     * @name: addLog
     * @describe:添加日志
     */
    function addLog($title='',$content='')
    {
        $log=new \app\admin\model\Logs();
        $safe=GetSysConfig("admin_log");
        if (isset($safe) && (int)$safe==1){ //是否开启网站后台日志
            $log->setTitle($title);
            $log->setContent($content);
            $log->record();
        }
    }
}



if (!function_exists('GetSysConfig')) {
    /**
     * 设备或配置系统参数
     * @param string $name 参数名称
     * @return string|boolean
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    function GetSysConfig($name)
    {
        $key = md5(config('database.hostname') . '#' . config('database.database').$name);
        if (Cache::has($key)){
            $data=Cache::get($key);
        }else{
            $data = Db::name('setting')->where("key","=", "{$name}")->value("value");
            Cache::set($key,$data,180);
        }
        return $data;
    }
}




